package com.fwx.sercvice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fwx.entity.Permission;
import com.fwx.entity.User;
import com.fwx.mapper.PermissionMapper;
import com.fwx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: springsecurity04
 * @description:
 * @author: 范文轩
 * @create: 2024-07-29 15:22
 **/

@Service
public class MyUserDetailsService implements UserDetailsService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.nonNull(user)){
            Collection<Permission> permissions = permissionMapper.selectByUserId(user.getUserid());
            List<SimpleGrantedAuthority> collect = permissions.stream().map(
                    item -> new SimpleGrantedAuthority(item.getPercode())
            ).collect(Collectors.toList());
            
            return new org.springframework.security.core.userdetails.User(username,user.getUserpwd(),collect);
        }
        
        return null;
    }
}
